package com.bristua.barcode.common.interceptor;

import com.bristua.barcode.common.enums.CommonCode;
import com.bristua.barcode.common.exception.BizException;
import com.bristua.barcode.common.util.HttpSessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class UserLoginHandlerInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(UserLoginHandlerInterceptor.class);

    @Autowired
    private HttpSessionUtil httpSessionUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestURI = request.getRequestURI();
        if(requestURI.contains("swagger")){
            return true;
        }
        String token = httpSessionUtil.getToken();
        if (StringUtils.isEmpty(token)) {
            throw new BizException(CommonCode.INVALID_REQUEST.getCode(), CommonCode.INVALID_REQUEST.getMsg());
        }

        if(httpSessionUtil.getUserInfo()==null){
            throw new BizException(CommonCode.INVALID_TOKEN.getCode(), CommonCode.INVALID_TOKEN.getMsg());
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        if (modelAndView != null) {
            modelAndView.addObject("basePath", basePath);
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
//        UserThreadLocal.set(null);
    }

}
